package com.zuper.demo.sessionlogin.web;

import java.util.Enumeration;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import com.zuper.demo.sessionlogin.base.BaseCtrller;
import com.zuper.demo.sessionlogin.base.BaseResult;
import com.zuper.demo.sessionlogin.constant.ErrorEnum;
import com.zuper.demo.sessionlogin.constant.SysConsts;
import com.zuper.demo.sessionlogin.entity.SysUser;

@RestController
public class TestCtrller extends BaseCtrller{
	//session失效化-for功能测试
	@GetMapping("/invalidateSession")
	public BaseResult invalidateSession(HttpServletRequest request) {
		HttpSession session = request.getSession(false);
		if(session != null && 
				session.getAttribute(SysConsts.Session_Login_Key)!=null) {
			request.getSession().invalidate();
			getServletContext().log("Session已注销！");
        }
		return new BaseResult(true);
	}
	
	//模拟普通ajax数据请求（待登录拦截的）
	@GetMapping("/hello")
	public BaseResult hello(HttpServletRequest request) {
		//headers
		request.getServletContext().log(">> print request headers");
		Enumeration<String> enumHeader =  request.getHeaderNames();
    	while(enumHeader.hasMoreElements()) {
    		String name = enumHeader.nextElement();
    		String value = request.getHeader(name);
    		getServletContext().log(name + ": " + value);
    	}
		
		getServletContext().log(">> 登录session未失效，继续正常流程！");
		return new BaseResult(true, "登录session未失效，继续正常流程！");
	}
	
	//登录接口
	@PostMapping("/login")
	public BaseResult login(@RequestBody SysUser dto, HttpServletRequest request) {
		//cookie信息 
		request.getServletContext().log(">> print request cookies");
		Cookie[] cookies = request.getCookies();
		if(null!=cookies && cookies.length>0) {
			for(Cookie c:cookies) {
				getServletContext().log(c.getName() + ": " + c.getValue());
			}
		}
		
		/**
		 * session处理
		 */
		//模拟库存数据
		SysUser entity = new SysUser();
		entity.setId(1);
		entity.setPassword("123456");
		entity.setUsername("Richard");
		entity.setNickname("Richard-管理员");
		//验密
		if(entity.getUsername().equals(dto.getUsername()) && entity.getPassword().equals(dto.getPassword())) {
            if(request.getSession(false) != null) {
            	getServletContext().log(">> 每次登录成功改变SessionID！");
                request.changeSessionId(); //安全考量，每次登陆成功改变 Session ID，原理：原来的session注销，拷贝其属性建立新的session对象
            }
            //新建/刷新session对象
            HttpSession session = request.getSession();
            getServletContext().log(">> sessionId: " + session.getId());
            session.setAttribute(SysConsts.Session_Login_Key, entity);
            
            entity.setId(null); //敏感数据不返回前端
            entity.setPassword(null);
            return new BaseResult(entity);
        } else {
        	return new BaseResult(ErrorEnum.Login_Incorrect);
        }
	}
}
